package com.shop.servlet.admin;

import com.shop.pajo.Admin;
import com.shop.service.admin.AdminServiceImpl;
import com.shop.service.admin.IAdminService;
import com.shop.utils.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AdminServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method=req.getParameter("method");
        if(method!=null && method.equals("login")){
            this.login(req,resp);
        }else if(method!=null && method.equals("logout")){
            this.logout(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    public void login(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        //获取用户名和密码
        String name = req.getParameter("adminCode");
        String password = req.getParameter("adminPassword");

        //和数据库中的密码进行对比；进行调用业务层
        IAdminService adminService=new AdminServiceImpl();
        Admin admin = adminService.getLoginAdmin(name,password);    //这里已经把登录的人查出来了
        if(admin!=null){//查到人了可以登录
            //将用户的信息放到Session中
            req.getSession().setAttribute(Constants.ADMIN_SESSION, admin);
            //跳转到内部主页
            resp.sendRedirect("/jsp/admin/admin.jsp");
        }else{//没有查到无法登录
            //转发回登录界面,提示用户名或密码错误
            req.setAttribute("error", "用户名或者密码不正确");
            req.getRequestDispatcher("/jsp/admin/adminLogin.jsp").forward(req, resp);
        }
    }
    public void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.getSession().removeAttribute(Constants.ADMIN_SESSION);
        resp.sendRedirect("/jsp/admin/adminLogin.jsp");
    }
}
